package com.infoland.afanmall.model.youXuan.fragment;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.google.zxing.Result;
import com.infoland.afanmall.R;
import com.infoland.afanmall.base.fragment.BaseLazyFragment;
import com.infoland.afanmall.base.util.CONST;
import com.infoland.afanmall.base.util.CacheKit;
import com.infoland.afanmall.base.util.LogKit;
import com.infoland.afanmall.base.util.StatusBarKit;
import com.infoland.afanmall.base.util.ToolsKit;
import com.infoland.afanmall.base.util.UserKit;
import com.infoland.afanmall.base.util.okhttp.OkHttpKit;
import com.infoland.afanmall.base.view.refreshHeader.Header;
import com.infoland.afanmall.model.eventBus.main.RefBus;
import com.infoland.afanmall.model.pinTuan.activity.PinTuanActivity;
import com.infoland.afanmall.model.shopCart.activity.ShopCartActivity;
import com.infoland.afanmall.model.shopCart.entity.ShopCartEntity;
import com.infoland.afanmall.model.xilie.activity.XiLieListActivity;
import com.infoland.afanmall.model.youXuan.activity.GoodInfoActivity;
import com.infoland.afanmall.model.youXuan.activity.SearchActivity;
import com.infoland.afanmall.model.xilie.activity.XiLieActivity;
import com.infoland.afanmall.model.youXuan.adapter.YouXuanAdapter;
import com.infoland.afanmall.model.youXuan.entity.BannerEntity;
import com.infoland.afanmall.model.youXuan.entity.OptionEntity;
import com.infoland.afanmall.model.youXuan.entity.PtParaEntity;
import com.infoland.afanmall.model.youXuan.entity.PtResponse;
import com.infoland.afanmall.model.youXuan.entity.TimeByEntity;
import com.infoland.afanmall.model.youXuan.entity.YouXuanType;
import com.infoland.afanmall.model.zhongChou.activity.ZhongChouActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.vondear.rxtools.RxPermissionsTool;
import com.vondear.rxtools.activity.ActivityScanerCode;
import com.vondear.rxtools.interfaces.OnRxScanerListener;
import com.wang.avi.AVLoadingIndicatorView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class YouXuanFragment extends BaseLazyFragment {
    //
    int color;
    int lastScrollY = 0;
    int mixHight;
    private int mScrollY = 0;
    private int scroolHeight = 0;// 滑动开始变色的高,真实项目中此高度是由广告轮播或其他首页view高度决定
    protected YouXuanAdapter youXuanAdapter; //适配器
    protected ArrayList<MultiItemEntity> entityList;//数据源
    LinearLayoutManager linearLayoutManager;
    //
    Unbinder unbinder;
    @BindView(R.id.avi_pt)
    AVLoadingIndicatorView aviPt;
    @BindView(R.id.ys_search)
    EditText ys_search;
    @BindView(R.id.ys_scan)
    ImageView ys_scan;
    @BindView(R.id.ys_cart)
    ImageView ys_cart;
    @BindView(R.id.you_xuan_tab)
    LinearLayout you_xuan_tab;
    @BindView(R.id.pt_bt_zh)
    RadioButton pt_bt_zh;
    @BindView(R.id.pt_bt_xl)
    RadioButton pt_bt_xl;
    @BindView(R.id.pt_bt_jg)
    RadioButton pt_bt_jg;
    @BindView(R.id.pt_bt_zx)
    RadioButton pt_bt_zx;
    //
    @BindView(R.id.net_scro)
    NestedScrollView net_scro;
    @BindView(R.id.ys_you_ll)
    LinearLayout ys_you_ll;//圆点布局
    @BindView(R.id.ys_you_ll_text_2)
    AppCompatTextView ys_you_ll_text_2;//圆点数量
    //
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;//刷新布局
    @BindView(R.id.youxuan_rv)
    RecyclerView mRecyclerView;
    @BindView(R.id.ys_title)
    LinearLayout title;
    @BindView(R.id.you_xuan_scan)
    LinearLayout you_xuan_scan;
    @BindView(R.id.you_xuan_cart)
    RelativeLayout you_xuan_cart;

    @Override
    public int getLayout() {
        return R.layout.you_xuan_fragment;
    }

    @Override
    public void initData() {
        startLoading();
        StatusBarKit.immersive(getActivity()); //设置当前activity为沉浸
        StatusBarKit.setPaddingSmart(getActivity(), title);//只能添加padding
        ToolsKit.setEditHide(ys_search);//设置搜索框不可输入
        Header header = new Header(getActivity());
        header.setShowAndCloseView(title);
        refreshLayout.setRefreshHeader(header);
        refreshLayout.setHeaderHeight(60);
        linearLayoutManager = new LinearLayoutManager(CacheKit.APP_CONTEXT);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mixHight = DensityUtil.dp2px(170);
        color = ContextCompat.getColor(CacheKit.APP_CONTEXT, R.color.gray_dark_bg) & 0x00ffffff;
        pt_bt_zh.setChecked(true);
        title.setBackgroundColor(0);
        /***开始查询*/
        initYouXuanData();
        /*** 获取购物车数量**/
        getCartCount();
        /****添加渐变色*/
        addTitleJianBian();
    }

    //扫描二维码*/
    private void sacnErWeiMa() {
        List<String> strings = RxPermissionsTool.
                with(CacheKit.ACTIVITY).
                addPermission(Manifest.permission.CAMERA).initPermission();
        LogKit.E("  strings ", "  " + strings);
        LogKit.E("  strings ", "  " + strings.size());
        ActivityScanerCode.setScanerListener(new OnRxScanerListener() {
            @Override
            public void onSuccess(String s, Result result) {
                LogKit.E("  result ", "  " + result);
                LogKit.E("  s ", "  " + s);
            }

            @Override
            public void onFail(String s, String s1) {
                LogKit.E(" s1  ", "  " + s1);
                LogKit.E(" s  ", "  " + s);

            }
        });
        ToolsKit.goDh(getActivity(), ActivityScanerCode.class);
    }

    //开始查询*/
    private void initYouXuanData() {
        entityList = new ArrayList<>();
        getBanner();
    }

    //获取，banner页**/
    public void getBanner() {
        JSONObject para = new JSONObject();
        para.put("placeType", "sylb");
        new OkHttpKit().send(
                response200 -> {
                    LogKit.E("banner ---->   ", "  " + response200);
                    List<BannerEntity> list = JSONArray.parseArray(response200, BannerEntity.class);
                    BannerEntity bannerEntity = new BannerEntity();
                    bannerEntity.list = list;
                    entityList.add(bannerEntity);
                    initAdapter();
                    adapterListener();
                    getOption();
                },
                error -> {
                    LogKit.E("error ---->   ", "  网络异常" + error);
                }
        ).post(CONST.BANNER_YX, para, getActivity());
    }

    //获取 频道信息**/
    public void getOption() {
        String url = CONST.HTTP + CONST.OPTION_YX;
        JSONObject para = new JSONObject();
        para.put("placeType", "sy_dh");
        new OkHttpKit().send(
                response200 -> {
                    List<OptionEntity> list = JSONArray.parseArray(response200, OptionEntity.class);
                    LogKit.E("  频道信息---> ", response200);
                    OptionEntity optionEntity = new OptionEntity();
                    optionEntity.list = list;
                    youXuanAdapter.addData(optionEntity);
                    youXuanAdapter.loadMoreComplete();
                    getTimeBy();
                },
                error -> {
                    LogKit.E("  频道信息---> ", error);
                }
        ).post(CONST.OPTION_YX, para, getActivity());
    }

    //获取  爆款信息**/
    public void getTimeBy() {
        LogKit.E("getTimeBy.....   ", " getTimeBy ");
        JSONObject jsonObject = new JSONObject();
//        1为热销，null为所有，0为非热销
        jsonObject.put("isHot", "1");
        new OkHttpKit().send(
                response200 -> {
                    LogKit.E("  爆款信息---> ", response200);
                    TimeByEntity timeByEntity = JSONObject.parseObject(response200, TimeByEntity.class);
                    youXuanAdapter.addData(timeByEntity);
                    youXuanAdapter.loadMoreComplete();
                    getPtFirst();
                },
                error -> {
                    LogKit.E("爆款信息 ---->   ", "  " + error);
                }
        ).post(CONST.OPTION_PT, jsonObject, getActivity());
    }

    //获取  普通商品信息**/
    public void getPtFirst() {
        LogKit.E("getPtFirst.....   ", " getPtFirst ");
        JSONObject para = getPtPara();
        JSONObject params = new JSONObject();
        params.put("pageNumber", 1);
        params.put("pageSize", 10);
        new OkHttpKit().send(
                response200 -> {
                    LogKit.E("  普通商品信息---> ", response200);
                    PtResponse ptEntity = JSONObject.parseObject(response200, PtResponse.class);
                    youXuanAdapter.addData(ptEntity);
                    youXuanAdapter.loadMoreComplete();
                    stopLoading();
                },
                error -> {
                    LogKit.E("普通商品信息 ---->   ", "  " + error);
                }
        ).post(CONST.OPTION_PT, para, getActivity());
    }

    //获取  购物车商品数量**/
    public void getCartCount() {
        LogKit.E("getCartCount.....   ", " getCartCount ");
        new OkHttpKit().send(
                response200 -> {
                    List<ShopCartEntity> shopCartEntities = JSONArray.parseArray(response200, ShopCartEntity.class);
                    if (shopCartEntities.size() > 0) {
                        List<ShopCartEntity.CartListBean> cartList = shopCartEntities.get(0).getCartList();
                        if (cartList.size() > 0) {
                            ys_you_ll.setVisibility(View.VISIBLE);
                            ys_you_ll_text_2.setText("" + cartList.size());
                        }
                    } else {
                        ys_you_ll.setVisibility(View.GONE);
                    }
                },
                success401 -> {
                    ys_you_ll.setVisibility(View.GONE);
                },
                error -> {
                    LogKit.E("普通商品信息 ---->   ", "  " + error);
                }
        ).post(CONST.GET_USER_CART + UserKit.getAccessToken(), new JSONObject(), getActivity());
    }

    //初始化适配器
    private void initAdapter() {
        youXuanAdapter = new YouXuanAdapter(
                CacheKit.APP_CONTEXT,
                entityList,
                getActivity(),
                mRecyclerView,
                linearLayoutManager,
                refreshLayout,
                title);
        youXuanAdapter.setPt_bt_jg(pt_bt_jg);
        youXuanAdapter.setPt_bt_xl(pt_bt_xl);
        youXuanAdapter.setPt_bt_zh(pt_bt_zh);
        youXuanAdapter.setPt_bt_zx(pt_bt_zx);
        youXuanAdapter.setNet_scro(net_scro);
        mRecyclerView.setAdapter(youXuanAdapter);
    }

    //适配器，监听器**/
    private void adapterListener() {
        //        /*** 下拉刷新**/
        youXuanAdapter.setRefrenshLinster(refreshLayout -> {
            startLoading();
            initYouXuanData();
        });
        //       各种监听
        youXuanAdapter.setYXLinster((holder, itemType, position, item, item_type) -> {
            switch (itemType) {
                /**轮播图*/
                case YouXuanType.BANNER:
                    BannerEntity bannerEntity = (BannerEntity) item;
                    String ad_path_android = bannerEntity.getAd_path_android();
                    String[] split = ad_path_android.split("_");
                    String type = "";
                    if (split.length >= 2) {
                        type = split[0];
                    }
                    switch (type) {
                        case "zhongchou":
                            if (position < 2) {
                                ToolsKit.goDh(getActivity(), PinTuanActivity.class);
                            } else {
                                int activityId = Integer.valueOf(split[1]);
                                LogKit.E("zhongchou ---->   ", "  " + activityId);
                                Bundle bundle = new Bundle();
                                bundle.putInt("activityId", activityId);
                                ToolsKit.goDh(getActivity(), ZhongChouActivity.class, bundle);
                            }

                            break;
                        default:
                            break;
                    }
                    break;
                /**选项卡*/
                case YouXuanType.OPTION:
                    OptionEntity optionEntity = (OptionEntity) item;
                    LogKit.E("  item  ", "  " + optionEntity.getAd_name());
                    switch (optionEntity.getAd_name()) {
                        case "秒杀":
                            LogKit.E("秒杀", "  " + "  ");
                            break;
                        case "拼团":
                            ToolsKit.goDh(getActivity(), PinTuanActivity.class);
                            break;
                        case "众筹":
                            LogKit.E("众筹", "  " + "  ");
                            break;
                        case "系列":
                            ToolsKit.goDh(getActivity(), XiLieListActivity.class);
                            break;
                        default:
                            LogKit.E("   ", "  " + "  ");
                            break;
                    }
//                    GuiGeDialogFragment dialog_option = new GuiGeDialogFragment();
//                    dialog_option.show(getChildFragmentManager(), "dialog");
                    break;
                /**爆款*/
                case YouXuanType.TIME_BY:
                    TimeByEntity.ListBean objectBean = (TimeByEntity.ListBean) item;
                    switch (item_type) {
                        case "img":
                            Bundle b = new Bundle();
                            b.putInt("id", objectBean.getId());
                            /*** 去品详情页**/
                            ToolsKit.goDh(getActivity(), GoodInfoActivity.class, b);
                            break;
                        case "btn":
                            ToolsKit.openGuiGeTrue((AppCompatActivity) getActivity(), objectBean.getId(), CONST.OPEN_NOW_BY);
                            break;
                        default:
                            break;
                    }
                    break;
                /**普通商品*/
                case YouXuanType.PT:
                    PtResponse.ListBean listBean = (PtResponse.ListBean) item;
                    LogKit.E("   listBean", "  " + listBean.toString());
                    switch (item_type) {
                        case "img":
                            Bundle b = new Bundle();
                            b.putInt("id", listBean.getId());
                            /*** 去品详情页**/
                            ToolsKit.goDh(getActivity(), GoodInfoActivity.class, b);
                            break;
                        case "xin":
                            ToastUtils.showShort("收藏。。。。");
                            LogKit.E(" itemType  ", "  " + item_type);
                            break;
                        case "cart":
                            ToolsKit.openGuiGeTrue((AppCompatActivity) getActivity(), listBean.getId(), CONST.OPEN_INSERT_CART);
                            break;
                        case "xi_lie":
//                            ToolsKit.go(XiLieActivity.class);
                            ToolsKit.goDh(getActivity(), XiLieActivity.class);
                            ToastUtils.showShort(" 系列商品，暂时没有");
//                            ToolsKit.openGuiGe(activity, listBean.getId(), CONST.OPEN_INSERT_CART);
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }

        });
    }

    public JSONObject getPtPara() {
        PtParaEntity entity = new PtParaEntity();
        entity.setPageNumber(1);
        entity.setPageSize(10);
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(entity);
        return jsonObject;
    }

    private void startLoading() {
        refreshLayout.setFocusableInTouchMode(true);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setEnableRefresh(false);
        aviPt.setVisibility(View.VISIBLE);
    }

    private void stopLoading() {
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
        aviPt.setVisibility(View.GONE);
    }

    //标题栏渐变色
    private void addTitleJianBian() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            net_scro.setOnScrollChangeListener((View.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
                if (lastScrollY < mixHight && scrollY > 0) {
                    scrollY = Math.min(mixHight, scrollY);
                    mScrollY = scrollY > mixHight ? mixHight : scrollY;
                    title.setBackgroundColor(((255 * mScrollY / mixHight) << 24) | color);
                } else {
                    //                LogKit.E(" 已经超出toolbar  ", "  已经超出toolbar");
                }
                lastScrollY = scrollY;
                View childAt0 = mRecyclerView.getChildAt(0);
                View childAt1 = mRecyclerView.getChildAt(1);
                View childAt2 = mRecyclerView.getChildAt(2);
                View childAt3 = mRecyclerView.getChildAt(3);
                if (childAt0 != null && childAt1 != null && childAt2 != null && childAt3 != null) {
                    int threeHeight = childAt0.getHeight() + childAt1.getHeight() + childAt2.getHeight();
                    int height = title.getHeight();
                    if (scrollY + height >= threeHeight) {
                        you_xuan_tab.setVisibility(View.VISIBLE);
                    } else {
                        you_xuan_tab.setVisibility(View.GONE);
                    }
                } else {
                    you_xuan_tab.setVisibility(View.GONE);
                }
            });
        }

    }

    @OnClick({R.id.ys_search, R.id.you_xuan_scan, R.id.you_xuan_cart})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            /****点击扫描二维码**/
            case R.id.you_xuan_scan:
                sacnErWeiMa();
                break;
            /****点击购物车**/
            case R.id.you_xuan_cart:
                ToolsKit.go(ShopCartActivity.class);
                break;
            /***点击搜索框**/
            case R.id.ys_search:
                ToolsKit.goDh(getActivity(), SearchActivity.class);
                break;
        }
    }

    //展示并刷新界面
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refAndShowLayout(RefBus refBus) {
        if (refBus != null) {
            if (refBus.getFragmentId() == 1) {
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
                LogKit.E("refAndShowLayout ---->   ", "  Story");
                startLoading();
                initYouXuanData();
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(getLayout(), null);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        ToolsKit.deleteOKHttp(getActivity());
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onResume() {
        super.onResume();
        getCartCount();
    }

}


//    /****添加渐变色*/
//    private void addJianBianSe() {
//        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//            }
//
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//                scroolHeight += dy;
//                int overallXScroll = scroolHeight;
////                int height = title.getHeight();
////                if (overallXScroll + height >= fuDongHeight) {
////                    you_xuan_tab.setVisibility(View.VISIBLE);
////                } else {
////                    you_xuan_tab.setVisibility(View.GONE);
////                }
//                if (lastScrollY < mixHight && overallXScroll > 0) {
//                    overallXScroll = Math.min(mixHight, overallXScroll);
//                    mScrollY = overallXScroll > mixHight ? mixHight : overallXScroll;
//                    title.setBackgroundColor(((255 * mScrollY / mixHight) << 24) | color);
//                } else {
////                    LogKit.E(" 已经超出toolbar  ", "  已经超出toolbar");
//                }
//                lastScrollY = overallXScroll;
//            }
//        });
//    }

